package pers.jason.wppm.security.core.social.oicq.api;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;
import pers.jason.wppm.security.core.exception.SocialAuthenticationException;
import pers.jason.wppm.security.core.social.oicq.dto.OicqUser;

import java.io.IOException;

/**
 * API组件：
 *  使用token请求用户的openid
 *  使用token、openid请求用户基本信息
 *  基类AbstractOAuth2ApiBinding中已经提供私有属性accesstoken
 */
public class OicqApiBindingImpl extends AbstractOAuth2ApiBinding implements OicqApiBinding {

    private String appId;

    private String openId;

    private ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 请求OPENID的URL
     */
    private static final String URL_REQUEST_OPENID_GET = "https://graph.qq.com/oauth2.0/me?access_token=%s";

    /**
     * 请求用户基本信息
     * 其中accesstolen由springsocial封装进请求
     */
    private static final String URL_REQUEST_USERINFO_GET = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";

    public OicqApiBindingImpl(String accessToken, String appId) {
        /**
         * 涉及token的传递方式，QQ作为参数请求，因此使用TokenStrategy.ACCESS_TOKEN_PARAMETER
         */
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
        this.appId = appId;
        String url = String.format(URL_REQUEST_OPENID_GET, accessToken);
        String result = getRestTemplate().getForObject(url, String.class);
        this.openId = StringUtils.substringBetween(result, "\"openid\":\"", "\"}");
    }

    @Override
    public OicqUser getOicqUser() {
        String url = String.format(URL_REQUEST_USERINFO_GET, appId, openId);
        String result = getRestTemplate().getForObject(url, String.class);
        try {
            OicqUser oicqUser = objectMapper.readValue(result, OicqUser.class);
            oicqUser.setOpenId(openId);
            return oicqUser;
        } catch (IOException e) {
            e.printStackTrace();
            throw new SocialAuthenticationException("请求用户信息失败");
        }
    }
}
